import 'package:flutter/material.dart';

import 'select_area_code_page.dart';
import '../models/country_model.dart';
import '../network/echo/echo_network.dart';
import '../network/base/network_response.dart';

class CheckPhoneRegisteredPage extends StatefulWidget {
  CheckPhoneRegisteredPage() : super();
  @override
  _CheckPhoneRegisteredPageState createState() => _CheckPhoneRegisteredPageState();
}

class _CheckPhoneRegisteredPageState extends State<CheckPhoneRegisteredPage> {

  TextEditingController phoneController = TextEditingController();
  CountryInfo countryInfo = CountryInfo(countryName: '中国', phoneCode: '86');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: new Container(
          padding: new EdgeInsets.all(20.0),
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              new Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  new FlatButton(
                    child: Text('+'+countryInfo.phoneCode),
                    onPressed: _clickAreaButton,
                  ),
                  new Expanded(
                    child: new TextField(
                      controller: phoneController,
                      keyboardType: TextInputType.number,
                      decoration: new InputDecoration(
                        hintText: '请输入手机号',
                      ),
                      autofocus: true,
                      style: TextStyle(fontSize: 16.0, color: Colors.black),
                      onChanged: (text) {
//                        print('change $text');
                      },
                    ),
                  )
                ],
              ),
              new RawMaterialButton(
                onPressed: _clickNextButton,
                child: Text('下一步'),
              ),
            ],
          ),
        )
    );
  }

  //点击下一步按钮
  void _clickNextButton() {
    if (this.phoneController.text.length < 1) {
      showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: Text('手机号码格式不对'),
          ));
    } else {
      _checkPhoneRequest();
      this.phoneController.clear();
    }
  }

  //点击区号按钮
  void _clickAreaButton() {
    Navigator.push(
        context,
        new MaterialPageRoute(builder: (context) => new SelectAreaCodePage(this.countryInfo))
    ).then((result) {
      if (result != null) {
        setState(() {
          this.countryInfo = result;
        });
      }
    });
  }

  //检查手机号是否注册过
  Future<void> _checkPhoneRequest() async {
    await EchoNetwork().post('/v1/check_phone_registered', params: {'phone':this.phoneController.text,'area_code':'+'+this.countryInfo.phoneCode} , successCallBack: (NetworkSuccessResponse successResponse) {
      print(successResponse);
    }, failureCallBack:  (NetworkFailureResponse failureResponse) {
      print(failureResponse);
    });
  }
}